<template>
    <div class="wrapper">
        <div class="header-item">
            <div class="header-item-info">
                <div class="header-item-title">安检速度</div>
                <p class="header-item-intro">{{ securityCheckSpeed }}人/分钟</p>
            </div>
            <div class="header-item-icon"></div>
        </div>
        <div class="header-item">
            <div class="header-item-info">
                <div class="security-check-item" v-for="item of securityCheckTypeList">
                    {{ item.label }}
                    <span class="security-check-num">{{ item.num }}</span>
                    <span class="suffix">人</span>
                </div>
            </div>
            <div class="header-item-icon"></div>
        </div>
        <div class="header-item">
            <div class="header-item-info">
                <div class="header-item-title">安检进度</div>
                <div class="progress-bar-wrapper">
                    <div class="progress-bar">
                        <div class="progress-bar-item" :class="{ actived: item.index < integer, incomplete: item.index === incompleteIndex }" :style="{ '--width': item.index === incompleteIndex ? decimal : 'auto' }" v-for="item of progressBar"></div>
                    </div>
                    <div class="progress-bar-text">{{ currentProgress }}%</div>
                </div>
            </div>
            <div class="header-item-icon"></div>
        </div>

        <aside class="aside">
            <div class="area-panel" v-for="item of areaList">
                <div class="area-count">
                    <span class="area-num">{{ item.areaNum }}</span>
                    <span class="area-total">/{{ item.total }}</span>
                </div>
                <p class="area-info">{{ item.area }}区（人）</p>
            </div>
        </aside>

        <div class="seat-wrapper">
            <template :key="index1" v-for="(area, index1) of list">
                <div class="seat-list">
                    <template :key="index" v-for="(item, index) of area.list">
                        <el-popover :width="300" popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;">

                            <template #reference>
                                <li class="seat-item" :class="[{ actived: item.isActived }, 'seat-item' + index1]" @mouseenter="onMouseenter(area.zone, item.row, item.column)"></li>
                            </template>
                            <template #default>
                                <div class="demo-rich-conent" style="display: flex; gap: 16px; flex-direction: column">
                                  <!-- <el-avatar
                                    :size="60"
                                    src="https://avatars.githubusercontent.com/u/72015883?v=4"
                                    style="margin-bottom: 8px"
                                  /> -->
                                  <div>
                                    <p style="margin: 0; font-weight: 500">身份证：{{ item.sfz }}</p>
                                    <p style="margin: 15px 0 0; font-weight: 500">姓名：{{ item.xm }}</p>
                                    <p style="margin: 15px 0 0; font-weight: 500">手机：{{ item.phone }}</p>
                                    <p style="margin: 15px 0 0; font-weight: 500">地址：{{ item.address }}</p>
                                    <p style="margin: 15px 0 0; font-weight: 500" v-if="item.isActived">通行时间：{{ item.date }}</p>
                                  </div>
                                </div>
                            </template>

                        </el-popover>
                    </template>
                </div>
            </template>

            <p class="seat-tip up">
                通
                <span class="text">道</span>
            </p>
            <p class="seat-tip right">通&#x3000;道</p>
            <p class="seat-tip down">
                通
                <span class="text">道</span>
            </p>
            <p class="seat-tip left">通&#x3000;道</p>
        </div>
    </div> 
</template>

<script setup>
import { ref, computed } from 'vue'
import axios from 'axios'

const securityCheckSpeed = ref('')
const securityCheckTypeList = ref([
    {
        label: '总人数',
        num: 0
    },
    {
        label: '已安检',
        num: 0
    },
    {
        label: '未安检',
        num: 0
    }
])

// 进度条
const progressBar = Array(10).fill(0).map((item, index) => ({ index }))
const currentProgress = ref(0)
const integer = computed(() => currentProgress.value > 10 ? Math.trunc(currentProgress.value / 10) : 0)
const incompleteIndex = computed(() => integer.value === 0 ? 0 : integer.value)
const decimal = computed(() => `${String(currentProgress.value / 10).split('.')[1]}0%`)

// 座位
const getSeatList = (row, column) => {
    const rows = Array(row).fill(0)
    const columns = Array(column).fill(0)
    const list = []

    columns.forEach((item, row) => {
        rows.forEach((item, column) => {
            list.push({
                row: row + 1,
                column: column +1,
                isActived: false
            })
        })
    })

    return list
}

const seatListA = ref(getSeatList(14, 7))
const seatListB = ref(getSeatList(14, 7))
const seatListC = ref(getSeatList(14, 7))
const seatListD = ref(getSeatList(14, 7))
const areaList = ref([
    {
        area: 'A',
        areaNum: 0,
        total: seatListA.value.length
    },
    {
        area: 'B',
        areaNum: 0,
        total: seatListB.value.length
    },
    {
        area: 'C',
        areaNum: 0,
        total: seatListC.value.length
    },
    {
        area: 'D',
        areaNum: 0,
        total: seatListD.value.length
    }
])
const list = ref([
    {
        zone: 'A',
        list: seatListA
    },
    {
        zone: 'B',
        list: seatListB
    },
    {
        zone: 'C',
        list: seatListC
    },
    {
        zone: 'D',
        list: seatListD
    }
])

// ws
const setStatisticsInfo = (data) => {
    const { speed, total, checked, unchecked, progress } = data

    securityCheckTypeList.value[0].num = total
    securityCheckTypeList.value[1].num = checked
    securityCheckTypeList.value[2].num = unchecked

    currentProgress.value = progress
    securityCheckSpeed.value = speed
}

const activeSeat = (data, zone) => {
    let list = data, area = zone

    if (! Array.isArray(data)) {
        list = [data]
        area = data.zone

        areaList.value.find((item) => item.area === data.zone).areaNum++
    }

    const map = {
        A: seatListA,
        B: seatListB,
        C: seatListC,
        D: seatListD
    }

    list.forEach((item) => {
        const seat = map[area].value.find(({ row, column }) => row === item.row && column === item.column)

        seat.isActived = true
    })
}
const map = {
    'zmt/19thHangzhou/security': activeSeat,
    'zmt/19thHangzhou/statistics': setStatisticsInfo
}
const client = mqtt.connect(import.meta.env.VITE_MQTT_URL, {
    clientId: 'mqttjs_zmt_:' + Date.now(),
    username: import.meta.env.VITE_MQTT_USERNAME,
    password: import.meta.env.VITE_MQTT_PASSWORD
})

client.subscribe('zmt/19thHangzhou/security')
client.subscribe('zmt/19thHangzhou/statistics')

client.on('error', (error) => {
    console.log('连接失败:', error)
})

client.on('message', (topic, message) => {
  console.log('收到消息：', topic, message.toString())

  map[topic](JSON.parse(message.toString()))
})

const http = axios.create({
    baseURL: import.meta.env.VITE_URL
})

// 统计信息
const getStatisticsInfo = async () => {
    try {
        const { data: res } = await http.post('/rshy/ydhy/statistics')
        

        if (res.errCode === 1) {
            setStatisticsInfo(res.data)
        } else {
            alert(res.errMsg)
        }
    } catch (e) {
        console.error(e)
    }
}

getStatisticsInfo()

// 当前安检列表
const getCheckedList = async (zone) => {
    try {
        const params = {
            zone
        }
        const { data: res } = await http.post('/rshy/ydhy/getCheckedList', params)

        if (res.errCode === 1) {
            areaList.value.find(({ area }) => area === zone).areaNum = res.data.length

            activeSeat(res.data, zone)
        } else {
            alert(res.errMsg)
        }
    } catch (e) {
        console.error(e)
    }
}

areaList.value.forEach(({ area }) => getCheckedList(area))

// 人员信息
const getPersonInfo = async (zone, row, column) => {
    try {
        const { data: res } = await http.post('/rshy/ydhy/getPersonInfo', {
            zone,
            row,
            column
        })

        if (res.errCode === 1) {
            const { xm, phone, address, sfz, timestamp } = res.data
            const map = {
                A: seatListA,
                B: seatListB,
                C: seatListC,
                D: seatListD
            }

            const seat = map[zone].value.find((item) => row === item.row && column === item.column)

            seat.xm = xm
            seat.phone = phone
            seat.sfz = sfz
            seat.address = address
            seat.date = new Date(timestamp).toLocaleString()
        } else {
            console.log(res.errMsg)
        }
    } catch (e) {
        console.error(e)
    }
}
const onMouseenter = (... params) => {
    clearTimeout(window.timer)

    window.timer = setTimeout(() => {
        getPersonInfo(... params)
    }, 300)
}
</script>

<style>
* {
    padding: 0;
    margin: 0;
}
body {
    padding: 18px 20px 20px;
    background-color: #E7E1EF;
}
li {
    list-style: none;
}
</style>
<style src="./style/index.css" scoped></style>
